package com.example.login

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.RoutePath
import com.example.common.mvi.BaseMviActivity
import com.example.login.databinding.ActivityLoginBinding
import com.example.login.entity.LoginData
import com.example.login.intent.LoginViewIntent
import com.example.login.state.LoginUiState
import com.example.login.vm.LoginViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = RoutePath.ROUTE_LOGIN)
@AndroidEntryPoint
class LoginActivity : BaseMviActivity<ActivityLoginBinding>() {
    private val mViewModel:LoginViewModel by viewModels()
    var tv:Boolean = false
    override fun initViews() {
        mDataBinding.login1.setOnClickListener {
            var password = mDataBinding.pp.text.toString()
            var username = mDataBinding.uu.text.toString()
            loginToServer(password,username)
        }

        mDataBinding.tvS.setOnClickListener {
            if(tv == false){
                mDataBinding.phoneEditText.visibility = View.INVISIBLE
                mDataBinding.login.visibility = View.INVISIBLE
                mDataBinding.username.visibility = View.VISIBLE
                mDataBinding.password.visibility = View.VISIBLE
                mDataBinding.tvS.text = "验证码登录"
                tv = true
            }else{
                mDataBinding.phoneEditText.visibility = View.VISIBLE
                mDataBinding.login.visibility = View.VISIBLE
                mDataBinding.username.visibility = View.INVISIBLE
                mDataBinding.password.visibility = View.INVISIBLE
                mDataBinding.tvS.text = "密码登录"
                tv = false
            }
        }
    }

    private fun loginToServer(password: String, username: String) {
        lifecycleScope.launch {
            mViewModel.channel.send(LoginViewIntent.LoginToServer(password,username))
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_login

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is LoginUiState.LoginSuccess ->handLoginSuccess(it.data) //处理登录成功的逻辑
                is LoginUiState.LoginFailure ->showToastMessage(it.msg)
                else ->{}

            }
        }
    }


    private fun handLoginSuccess(data: Any) {
        ARouter.getInstance().build(RoutePath.ROUTE_MAIN_NAV).navigation()
        this@LoginActivity.finish()
    }

}